package com.hqq.leetcode.stack;

import java.util.Stack;

/**
 * SimplifyPath 简化路径
 * Description:
 * Given an absolute path for a file (Unix-style), simplify it.
 * Input:
 * /home/
 * /a/./b/../../c/
 * Output:
 * /home
 * /c
 * Created by heqianqian on 2017/9/17.
 */
public class SimplifyPath {

    public static void main(String[] args) {
        String path = new SimplifyPath().simplifyPath("/...");
        System.out.println(path);
    }

    /*
   * @param path: the original path
   * @return: the simplified path
   */
    public String simplifyPath(String path) {
        // write your code here
        String[] split = path.trim().split("/");
        Stack<String> stack = new Stack<>();
        //TODO 为啥continue无效
        //for (int i = 0; i < split.length; i++) {
        //    if (split[i].equals(".") || split.equals("")) {
        //        continue;
        //    } else if (split[i].equals("..")) {
        //        if (!stack.empty()) {
        //            stack.pop();
        //        }
        //    } else {
        //        stack.push(split[i]);
        //    }
        //}
        for (String str:split){
            switch (str){
                case ".":
                case "":
                    break;
                case "..":
                    if(!stack.empty()){
                        stack.pop();
                    }
                    break;
                default:
                    stack.push(str);
                    break;
            }
        }
        StringBuilder sb = new StringBuilder();
        if (stack.isEmpty()) {
            sb.append("/");
        }
        while (!stack.isEmpty()) {
            sb.insert(0, "/" + stack.pop());
        }
        return sb.toString();
    }
}
